/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2022/12/14 0:36:13
 *        Description: 暂无
 ***********************************************************************/


using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Filter;
using CoreCms.Net.Loging;
using CoreCms.Net.IServices;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Utility.Extensions;
using CoreCms.Net.Web.Admin.Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using SqlSugar;

namespace CoreCms.Net.Admin.Admin.Controllers
{
    /// <summary>
    /// 微信自动回复消息表
    ///</summary>
    [Description("微信自动回复消息表")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize]
    public class WeChatMessageResponseController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly IWeChatMessageResponseServices _weChatMessageResponseServices;

        /// <summary>
        /// 构造函数
        ///</summary>
        public WeChatMessageResponseController(IWebHostEnvironment webHostEnvironment
            , IWeChatMessageResponseServices weChatMessageResponseServices
            )
        {
            _webHostEnvironment = webHostEnvironment;
            _weChatMessageResponseServices = weChatMessageResponseServices;
        }

        #region 获取列表============================================================
        // POST: Api/WeChatMessageResponse/GetPageList
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<AdminUiCallBack> GetPageList()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<WeChatMessageResponse>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<WeChatMessageResponse, object>> orderEx = orderField switch
            {
                "id" => p => p.id,
                "messageRule" => p => p.messageRule,
                "category" => p => p.category,
                "matchKey" => p => p.matchKey,
                "textContent" => p => p.textContent,
                "imgTextContext" => p => p.imgTextContext,
                "imgTextUrl" => p => p.imgTextUrl,
                "imgTextLink" => p => p.imgTextLink,
                "meidaUrl" => p => p.meidaUrl,
                "meidaLink" => p => p.meidaLink,
                "enable" => p => p.enable,
                "isDefault" => p => p.isDefault,
                "remark" => p => p.remark,
                "sort" => p => p.sort,
                "createTime" => p => p.createTime,
                _ => p => p.id
            };

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选

            //序列 int
            var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
            //消息类型 int
            var messageRule = Request.Form["messageRule"].FirstOrDefault().ObjectToInt(0);
            if (messageRule > 0)
            {
                where = where.And(p => p.messageRule == messageRule);
            }
            //分类 int
            var category = Request.Form["category"].FirstOrDefault().ObjectToInt(0);
            if (category > 0)
            {
                where = where.And(p => p.category == category);
            }
            //匹配字符 nvarchar
            var matchKey = Request.Form["matchKey"].FirstOrDefault();
            if (!string.IsNullOrEmpty(matchKey))
            {
                where = where.And(p => p.matchKey.Contains(matchKey));
            }
            //文本回复内容 nvarchar
            var textContent = Request.Form["textContent"].FirstOrDefault();
            if (!string.IsNullOrEmpty(textContent))
            {
                where = where.And(p => p.textContent.Contains(textContent));
            }
            //图片回复内容 nvarchar
            var imgTextContext = Request.Form["imgTextContext"].FirstOrDefault();
            if (!string.IsNullOrEmpty(imgTextContext))
            {
                where = where.And(p => p.imgTextContext.Contains(imgTextContext));
            }
            //图片回复图片地址 nvarchar
            var imgTextUrl = Request.Form["imgTextUrl"].FirstOrDefault();
            if (!string.IsNullOrEmpty(imgTextUrl))
            {
                where = where.And(p => p.imgTextUrl.Contains(imgTextUrl));
            }
            //图片回复超链接 nvarchar
            var imgTextLink = Request.Form["imgTextLink"].FirstOrDefault();
            if (!string.IsNullOrEmpty(imgTextLink))
            {
                where = where.And(p => p.imgTextLink.Contains(imgTextLink));
            }
            //语音回复地址 nvarchar
            var meidaUrl = Request.Form["meidaUrl"].FirstOrDefault();
            if (!string.IsNullOrEmpty(meidaUrl))
            {
                where = where.And(p => p.meidaUrl.Contains(meidaUrl));
            }
            //语音回复超链接 nvarchar
            var meidaLink = Request.Form["meidaLink"].FirstOrDefault();
            if (!string.IsNullOrEmpty(meidaLink))
            {
                where = where.And(p => p.meidaLink.Contains(meidaLink));
            }
            //是否启用 bit
            var enable = Request.Form["enable"].FirstOrDefault();
            if (!string.IsNullOrEmpty(enable) && enable.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.enable == true);
            }
            else if (!string.IsNullOrEmpty(enable) && enable.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.enable == false);
            }
            //是否默认 bit
            var isDefault = Request.Form["isDefault"].FirstOrDefault();
            if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.isDefault == true);
            }
            else if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.isDefault == false);
            }
            //备注 nvarchar
            var remark = Request.Form["remark"].FirstOrDefault();
            if (!string.IsNullOrEmpty(remark))
            {
                where = where.And(p => p.remark.Contains(remark));
            }
            //排序 int
            var sort = Request.Form["sort"].FirstOrDefault().ObjectToInt(0);
            if (sort > 0)
            {
                where = where.And(p => p.sort == sort);
            }
            //创建时间 datetime
            var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                if (createTime.Contains("到"))
                {
                    var dts = createTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.createTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.createTime < dtEnd);
                }
                else
                {
                    var dt = createTime.ObjectToDate();
                    where = where.And(p => p.createTime > dt);
                }
            }

            //获取数据
            var list = await _weChatMessageResponseServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "数据调用成功!";
            return jm;
        }
        #endregion

        #region 首页数据============================================================
        // POST: Api/WeChatMessageResponse/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public AdminUiCallBack GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var weChatRequestRuleEnum = EnumHelper.EnumToList<GlobalEnumVars.WeChatRequestRuleEnum>();
            var weChatReplyCategory = EnumHelper.EnumToList<GlobalEnumVars.WeChatReplyCategory>();
            jm.data = new
            {
                weChatRequestRuleEnum,
                weChatReplyCategory,
            };

            return jm;
        }
        #endregion

        #region 创建数据============================================================
        // POST: Api/WeChatMessageResponse/GetCreate
        /// <summary>
        /// 创建数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("创建数据")]
        public AdminUiCallBack GetCreate()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };


            var weChatRequestRuleEnum = EnumHelper.EnumToList<GlobalEnumVars.WeChatRequestRuleEnum>();
            var weChatReplyMatchKeyType = EnumHelper.EnumToList<GlobalEnumVars.WeChatReplyMatchKeyType>();
            var weChatReplyType = EnumHelper.EnumToList<GlobalEnumVars.WeChatReplyType>();
            jm.data = new
            {
                weChatRequestRuleEnum,
                weChatReplyMatchKeyType,
                weChatReplyType,
            };

            return jm;
        }
        #endregion

        #region 创建提交============================================================
        // POST: Api/WeChatMessageResponse/DoCreate
        /// <summary>
        /// 创建提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("创建提交")]
        public async Task<AdminUiCallBack> DoCreate([FromBody] WeChatMessageResponse entity)
        {
            var jm = await _weChatMessageResponseServices.InsertAsync(entity);
            return jm;
        }
        #endregion

        #region 编辑数据============================================================
        // POST: Api/WeChatMessageResponse/GetEdit
        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑数据")]
        public async Task<AdminUiCallBack> GetEdit([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _weChatMessageResponseServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            var weChatRequestRuleEnum = EnumHelper.EnumToList<GlobalEnumVars.WeChatRequestRuleEnum>();
            var weChatReplyMatchKeyType = EnumHelper.EnumToList<GlobalEnumVars.WeChatReplyMatchKeyType>();
            var weChatReplyType = EnumHelper.EnumToList<GlobalEnumVars.WeChatReplyType>();
            jm.data = new
            {
                model,
                weChatRequestRuleEnum,
                weChatReplyMatchKeyType,
                weChatReplyType,
            };
            jm.code = 0;
            return jm;
        }
        #endregion

        #region 编辑提交============================================================
        // POST: Api/WeChatMessageResponse/Edit
        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑提交")]
        public async Task<AdminUiCallBack> DoEdit([FromBody] WeChatMessageResponse entity)
        {
            var jm = await _weChatMessageResponseServices.UpdateAsync(entity);
            return jm;
        }
        #endregion

        #region 删除数据============================================================
        // POST: Api/WeChatMessageResponse/DoDelete/10
        /// <summary>
        /// 单选删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("单选删除")]
        public async Task<AdminUiCallBack> DoDelete([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _weChatMessageResponseServices.ExistsAsync(p => p.id == entity.id, true);
            if (!model)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            jm = await _weChatMessageResponseServices.DeleteByIdAsync(entity.id);

            return jm;
        }
        #endregion

        #region 预览数据============================================================
        // POST: Api/WeChatMessageResponse/GetDetails/10
        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        public async Task<AdminUiCallBack> GetDetails([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _weChatMessageResponseServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;
            jm.data = model;

            return jm;
        }
        #endregion

        #region 设置是否启用============================================================
        // POST: Api/WeChatMessageResponse/DoSetenable/10
        /// <summary>
        /// 设置是否启用
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置是否启用")]
        public async Task<AdminUiCallBack> DoSetenable([FromBody] FMUpdateBoolDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _weChatMessageResponseServices.QueryByIdAsync(entity.id, false);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.enable = (bool)entity.data;

            var bl = await _weChatMessageResponseServices.UpdateAsync(p => new WeChatMessageResponse() { enable = oldModel.enable }, p => p.id == oldModel.id);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion

        #region 设置是否默认============================================================
        // POST: Api/WeChatMessageResponse/DoSetisDefault/10
        /// <summary>
        /// 设置是否默认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置是否默认")]
        public async Task<AdminUiCallBack> DoSetisDefault([FromBody] FMUpdateBoolDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _weChatMessageResponseServices.QueryByIdAsync(entity.id, false);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.isDefault = (bool)entity.data;

            var bl = await _weChatMessageResponseServices.UpdateAsync(p => new WeChatMessageResponse() { isDefault = oldModel.isDefault }, p => p.id == oldModel.id);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion

    }
}
